package src.main.java.com.pms.service;

import src.main.java.com.pms.util.InputUtil;
import src.main.java.com.pms.util.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;

public class AppointmentService {

    /**
     * 添加洗澡预约
     */
    public void addBathAppointment() {
        int petId = InputUtil.getInt("输入要预约洗澡的宠物ID: ");
        if (!validatePetId(petId)) return;

        if (hasAppointment(petId, "bath")) {
            System.out.println("该宠物已有未完成的洗澡预约");
            return;
        }

        String sql = "UPDATE Pets SET has_bath_appointment = 1 WHERE id = ? AND deleted = 0";
        updateAppointment(sql, petId, "洗澡");
    }

    /**
     * 添加疫苗预约
     */
    public void addVaccineAppointment() {
        int petId = InputUtil.getInt("输入要预约疫苗的宠物ID: ");
        if (!validatePetId(petId)) return;

        if (hasAppointment(petId, "vaccine")) {
            System.out.println("该宠物已有未完成的疫苗预约");
            return;
        }

        String sql = "UPDATE Pets SET has_vaccine_appointment = 1 WHERE id = ? AND deleted = 0";
        updateAppointment(sql, petId, "疫苗");
    }

    /**
     * 添加火化预约
     */
    public void addCremationAppointment() {
        int petId = InputUtil.getInt("输入要预约火化的宠物ID: ");
        if (!validatePetId(petId)) return;

        if (hasAppointment(petId, "cremation")) {
            System.out.println("该宠物已有未完成的火化预约");
            return;
        }

        String sql = "UPDATE Pets SET has_cremation_appointment = 1 WHERE id = ? AND deleted = 0";
        updateAppointment(sql, petId, "火化");
    }

    /**
     * 查看预约
     */
    public void viewAppointments(String type) {
        String condition = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment = 1";
            case "vaccine" -> "has_vaccine_appointment = 1";
            case "cremation" -> "has_cremation_appointment = 1";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "SELECT * FROM Pets WHERE " + condition + " AND deleted = 0";
        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql)) {
            boolean found = false;
            System.out.println("\n当前" + type + "预约列表：");
            while (rs.next()) {
                found = true;
                printAppointmentInfo(rs, type);
            }
            if (!found) {
                System.out.println("没有找到" + type + "预约记录");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("查看预约时发生错误: " + e.getMessage());
        }
    }

    /**
     * 取消预约
     */
    public void cancelAppointment(String type) {
        int petId = InputUtil.getInt("输入要取消预约的宠物ID: ");
        if (!validatePetId(petId)) return;

        if (!hasAppointment(petId, type)) {
            System.out.println("该宠物没有" + type + "预约");
            return;
        }

        String column = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment";
            case "vaccine" -> "has_vaccine_appointment";
            case "cremation" -> "has_cremation_appointment";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "UPDATE Pets SET " + column + " = 0 WHERE id = ? AND deleted = 0";
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, petId);
            if (result > 0) {
                System.out.println(type + "预约取消成功！");
            } else {
                System.out.println("取消预约失败，可能该宠物不存在或已被删除");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("取消预约时发生错误: " + e.getMessage());
        }
    }

    /**
     * 完成预约
     */
    public void completeAppointment(String type) {
        int petId = InputUtil.getInt("输入要完成预约的宠物ID: ");
        if (!validatePetId(petId)) return;

        if (!hasAppointment(petId, type)) {
            System.out.println("该宠物没有" + type + "预约");
            return;
        }

        String column = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment";
            case "vaccine" -> "has_vaccine_appointment";
            case "cremation" -> "has_cremation_appointment";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "UPDATE Pets SET " + column + " = 0 WHERE id = ? AND deleted = 0";
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, petId);
            if (result > 0) {
                System.out.println(type + "预约已完成！");
            } else {
                System.out.println("完成预约失败，可能该宠物不存在或已被删除");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("完成预约时发生错误: " + e.getMessage());
        }
    }

    /**
     * 查看所有预约
     */
    public void viewAllAppointments() {
        String sql = "SELECT * FROM Pets WHERE (has_bath_appointment = 1 OR has_vaccine_appointment = 1 OR has_cremation_appointment = 1) AND deleted = 0";
        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql)) {
            boolean found = false;
            System.out.println("\n所有预约列表：");
            while (rs.next()) {
                found = true;
                System.out.println("\n宠物ID: " + rs.getInt("id") +
                        ", 名字: " + rs.getString("name") +
                        ", 类型: " + rs.getString("type") +
                        ", 年龄: " + rs.getInt("age"));

                if (rs.getInt("has_bath_appointment") == 1) {
                    System.out.println("- 有未完成的洗澡预约");
                }
                if (rs.getInt("has_vaccine_appointment") == 1) {
                    System.out.println("- 有未完成的疫苗预约");
                }
                if (rs.getInt("has_cremation_appointment") == 1) {
                    System.out.println("- 有未完成的火化预约");
                }
            }
            if (!found) {
                System.out.println("当前没有任何预约记录");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("查看预约时发生错误: " + e.getMessage());
        }
    }

    /**
     * 验证宠物ID
     */
    private boolean validatePetId(int petId) {
        if (petId <= 0) {
            System.out.println("宠物ID必须大于0");
            return false;
        }

        String sql = "SELECT id FROM Pets WHERE id = ? AND deleted = 0";
        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql, petId)) {
            if (!rs.next()) {
                System.out.println("未找到该宠物或宠物已被删除");
                return false;
            }
            return true;
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("验证宠物ID时发生错误: " + e.getMessage());
            return false;
        }
    }

    /**
     * 检查是否有预约
     */
    private boolean hasAppointment(int petId, String type) {
        String column = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment";
            case "vaccine" -> "has_vaccine_appointment";
            case "cremation" -> "has_cremation_appointment";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "SELECT " + column + " FROM Pets WHERE id = ? AND deleted = 0";
        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql, petId)) {
            return rs.next() && rs.getInt(1) == 1;
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("检查预约状态时发生错误: " + e.getMessage());
            return false;
        }
    }

    /**
     * 更新预约状态
     */
    private void updateAppointment(String sql, int petId, String type) {
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, petId);
            if (result > 0) {
                System.out.println(type + "预约添加成功！");
            } else {
                System.out.println("预约失败，可能该宠物不存在或已被删除");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("添加预约时发生错误: " + e.getMessage());
        }
    }

    /**
     * 打印预约信息
     */
    private void printAppointmentInfo(ResultSet rs, String type) throws SQLException {
        System.out.println("\n宠物ID: " + rs.getInt("id") +
                ", 名字: " + rs.getString("name") +
                ", 类型: " + rs.getString("type") +
                ", 年龄: " + rs.getInt("age") +
                ", 预约类型: " + type);
    }

    /**
     * 添加洗澡预约（GUI版本）
     */
    public boolean addBathAppointment(int petId) throws SQLException, ClassNotFoundException {
        if (!validatePetId(petId)) return false;
        if (hasAppointment(petId, "bath")) return false;

        String sql = "UPDATE Pets SET has_bath_appointment = 1 WHERE id = ? AND deleted = 0";
        int result = JDBCUtil.executeUpdateWithParams(sql, petId);
        return result > 0;
    }
    /**
     * 添加火化预约（GUI版本）
     */
    public boolean addCremationAppointmentByGUI(int petId) throws SQLException, ClassNotFoundException {
        if (!validatePetId(petId)) return false;
        if (hasAppointment(petId, "cremation")) return false;

        String sql = "UPDATE Pets SET has_cremation_appointment = 1 WHERE id = ? AND deleted = 0";
        int result = JDBCUtil.executeUpdateWithParams(sql, petId);
        return result > 0;
    }
    /**
     * 添加疫苗预约（GUI版本）
     */
    public boolean addVaccineAppointmentDialogByGUI(int petId) throws SQLException, ClassNotFoundException {
        if (!validatePetId(petId)) return false;
        if (hasAppointment(petId, "vaccine")) return false;

        String sql = "UPDATE Pets SET has_vaccine_appointment = 1 WHERE id = ? AND deleted = 0";
        int result = JDBCUtil.executeUpdateWithParams(sql, petId);
        return result > 0;
    }

    /**
     * 获取所有预约（GUI版本）
     */
    public ResultSet getAllAppointments() throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM Pets WHERE (has_bath_appointment = 1 OR " +
                    "has_vaccine_appointment = 1 OR has_cremation_appointment = 1) " +
                    "AND deleted = 0";
        return JDBCUtil.executeQueryWithConnection(sql);
    }

    /**
     * 获取特定类型的预约（GUI版本）
     */
    public ResultSet getAppointmentsByType(String type) throws SQLException, ClassNotFoundException {
        String column = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment";
            case "vaccine" -> "has_vaccine_appointment";
            case "cremation" -> "has_cremation_appointment";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "SELECT * FROM Pets WHERE " + column + " = 1 AND deleted = 0";
        return JDBCUtil.executeQueryWithConnection(sql);
    }

    /**
     * 取消预约
     */
    public void cancelAppointment(int petId, String type) {
        String column = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment";
            case "vaccine" -> "has_vaccine_appointment";
            case "cremation" -> "has_cremation_appointment";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "UPDATE Pets SET " + column + " = 0 WHERE id = ? AND deleted = 0";
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, petId);
            if (result > 0) {
                System.out.println(type + "预约取消成功！");
            } else {
                System.out.println("取消预约失败，可能该宠物不存在或已被删除");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("取消预约时发生错误: " + e.getMessage());
        }
    }

    /**
     * 更新预约状态
     */
    public void updateAppointment(int petId, String type, boolean hasAppointment) {
        String column = switch (type.toLowerCase()) {
            case "bath" -> "has_bath_appointment";
            case "vaccine" -> "has_vaccine_appointment";
            case "cremation" -> "has_cremation_appointment";
            default -> throw new IllegalArgumentException("无效的预约类型");
        };

        String sql = "UPDATE Pets SET " + column + " = ? WHERE id = ? AND deleted = 0";
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, hasAppointment ? 1 : 0, petId);
            if (result > 0) {
                System.out.println(type + "预约更新成功！");
            } else {
                System.out.println("更新预约失败，可能该宠物不存在或已被删除");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("更新预约时发生错误: " + e.getMessage());
        }
    }


}